#include "BinaryTree.h"
#include "Queue.h"

int TreeSize(BTNode* root)
{
	return root == NULL ? 0 : TreeSize(root->left)+TreeSize(root->right)+1;
}

int TreeLeafSize(BTNode* root)
{
	if (root == NULL)
		return 0;

	if (root->left == NULL && root->right == NULL)
		return 1;

	return TreeLeafSize(root->left)+TreeLeafSize(root->right);
}

void PrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
	}

	printf("%d ", root->data);
	PrevOrder(root->left);
	PrevOrder(root->right);
}

void InOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
	}

	InOrder(root->left);
	printf("%d ", root->data);
	InOrder(root->right);
}

void PostOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("N ");
		return;
	}

	PostOrder(root->left);
	PostOrder(root->right);
	printf("%d ", root->data);
}

int TreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
		return 0;

	if (k == 1)
		return 1;

	return TreeLevelKSize(root->left, k - 1)+TreeLevelKSize(root->right, k - 1);
}

BTNode* TreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
		return NULL;

	if (root->data == x)
		return root;

	BTNode* ret1 = TreeFind(root->left, x);
	if (ret1)
		return ret1;

	BTNode* ret2 = TreeFind(root->right, x);
	if (ret2)
		return ret2;

	return NULL;

	//return TreeFind(root->right, x);
}

BTNode* BinaryTreeCreate(BTDataType* a, int n, int* pi)
{
	//"ABD##E#H##CF##G##"
	if (a[*pi] == '#')
	{
		(*pi)++;
		return NULL;
	}

	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(EXIT_FAILURE);
	}

	node->data = a[(*pi)++];
	node->left = BinaryTreeCreate(a, n, pi);
	node->right = BinaryTreeCreate(a, n, pi);

	return node;
}

void TreeDestroy(BTNode** root)
{
	if (*root == NULL)
		return;

	if ((*root)->left == NULL && (*root)->right == NULL)
	{
		free(*root);
		*root = NULL;
		return;
	}

	TreeDestroy(&(*root)->left);
	TreeDestroy(&(*root)->right);
	TreeDestroy(root);
}

//void TreeDestroy(BTNode* root)
//{
//	if (root == NULL)
//		return;
//
//	TreeDestroy(root->left);
//	TreeDestroy(root->right);
//	free(root);
//}

void LevelOrder(BTNode* root)
{
	Queue q;
	QueueInit(&q);

	if (root)
		QueuePush(&q, root);

	while (!QueueEmpty(&q))
	{
		BTNode* front = QueueFront(&q);
		QueuePop(&q);

		printf("%d ", front->data);

		if (front->left)
			QueuePush(&q, front->left);

		if (front->right)
			QueuePush(&q, front->right);
	}

	QueueDestroy(&q);
}
